{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "# Simple custom layer example: Antirectifier\n",
    "\n",
    "**Author:** [fchollet](https://twitter.com/fchollet)<br>\n",
    "**Date created:** 2016/01/06<br>\n",
    "**Last modified:** 2020/04/20<br>\n",
    "**Description:** Demonstration of custom layer creation."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "## Introduction\n",
    "\n",
    "This example shows how to create custom layers, using the Antirectifier layer\n",
    " (originally proposed as a Keras example script in January 2016), an alternative\n",
    "to ReLU. Instead of zeroing-out the negative part of the input, it splits the negative\n",
    " and positive parts and returns the concatenation of the absolute value\n",
    "of both. This avoids loss of information, at the cost of an increase in dimensionality.\n",
    " To fix the dimensionality increase, we linearly combine the\n",
    "features back to a space of the original size.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "## Setup\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "import tensorflow as tf\n",
    "from tensorflow import keras\n",
    "from tensorflow.keras import layers\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "## The Antirectifier layer\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "\n",
    "class Antirectifier(layers.Layer):\n",
    "    def __init__(self, initializer=\"he_normal\", **kwargs):\n",
    "        super(Antirectifier, self).__init__(**kwargs)\n",
    "        self.initializer = keras.initializers.get(initializer)\n",
    "\n",
    "    def build(self, input_shape):\n",
    "        output_dim = input_shape[-1]\n",
    "        self.kernel = self.add_weight(\n",
    "            shape=(output_dim * 2, output_dim),\n",
    "            initializer=self.initializer,\n",
    "            name=\"kernel\",\n",
    "            trainable=True,\n",
    "        )\n",
    "\n",
    "    def call(self, inputs):\n",
    "        inputs -= tf.reduce_mean(inputs, axis=-1, keepdims=True)\n",
    "        pos = tf.nn.relu(inputs)\n",
    "        neg = tf.nn.relu(-inputs)\n",
    "        concatenated = tf.concat([pos, neg], axis=-1)\n",
    "        mixed = tf.matmul(concatenated, self.kernel)\n",
    "        return mixed\n",
    "\n",
    "    def get_config(self):\n",
    "        # Implement get_config to enable serialization. This is optional.\n",
    "        base_config = super(Antirectifier, self).get_config()\n",
    "        config = {\"initializer\": keras.initializers.serialize(self.initializer)}\n",
    "        return dict(list(base_config.items()) + list(config.items()))\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "## Let's test-drive it on MNIST\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "# Training parameters\n",
    "batch_size = 128\n",
    "num_classes = 10\n",
    "epochs = 20\n",
    "\n",
    "# The data, split between train and test sets\n",
    "(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()\n",
    "\n",
    "x_train = x_train.reshape(-1, 784)\n",
    "x_test = x_test.reshape(-1, 784)\n",
    "x_train = x_train.astype(\"float32\")\n",
    "x_test = x_test.astype(\"float32\")\n",
    "x_train /= 255\n",
    "x_test /= 255\n",
    "print(x_train.shape[0], \"train samples\")\n",
    "print(x_test.shape[0], \"test samples\")\n",
    "\n",
    "# Build the model\n",
    "model = keras.Sequential(\n",
    "    [\n",
    "        keras.Input(shape=(784,)),\n",
    "        layers.Dense(256),\n",
    "        Antirectifier(),\n",
    "        layers.Dense(256),\n",
    "        Antirectifier(),\n",
    "        layers.Dropout(0.5),\n",
    "        layers.Dense(10),\n",
    "    ]\n",
    ")\n",
    "\n",
    "# Compile the model\n",
    "model.compile(\n",
    "    loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n",
    "    optimizer=keras.optimizers.RMSprop(),\n",
    "    metrics=[keras.metrics.SparseCategoricalAccuracy()],\n",
    ")\n",
    "\n",
    "# Train the model\n",
    "model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, validation_split=0.15)\n",
    "\n",
    "# Test the model\n",
    "model.evaluate(x_test, y_test)\n"
   ]
  }
 ],
 "metadata": {
  "colab": {
   "collapsed_sections": [],
   "name": "antirectifier",
   "private_outputs": false,
   "provenance": [],
   "toc_visible": true
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}